package com.doujiang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doujiang.domain.Rating;
import com.doujiang.mapper.RatingMapper;
import com.doujiang.service.IRatingService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

/**
 * 评分管理Service业务层处理
 * 
 * @author 王伟舰
 * @date 2025-07-19
 */
@Service
public class RatingServiceImpl extends ServiceImpl<RatingMapper, Rating> implements IRatingService
{
    @Override
    public List<Rating> getRatingsByUserId(Long userId) {
        QueryWrapper<Rating> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.orderByDesc("created_at");
        return this.list(queryWrapper);
    }
    /**
     * 查询某电影的平均评分
     * 刘跃
     * @param movieId 评分管理主键
     * @return 评分管理
     */
    @Override
    public BigDecimal selectRatingByMovieId(Long movieId) {
        LambdaQueryWrapper<Rating> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Rating::getMovieId, movieId);
        List<Rating> ratings = this.list(queryWrapper);
        if (ratings.isEmpty()) {
            return BigDecimal.ZERO;
        }
        BigDecimal sum = BigDecimal.ZERO;
        for (Rating r : ratings) {
            sum = sum.add(r.getScore());
        }
        return sum.divide(BigDecimal.valueOf(ratings.size()), 1, RoundingMode.HALF_UP);
    }
    @Override
    public List<Rating> getRatingsByMovieId(Long movieId) {
        return lambdaQuery().eq(Rating::getMovieId, movieId).list();
    }

    @Override
    public boolean saveRating(Rating rating) {
        // 先查询是否已存在该用户对该电影的评分
        LambdaQueryWrapper<Rating> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Rating::getUserId, rating.getUserId())
                   .eq(Rating::getMovieId, rating.getMovieId());
        
        Rating existingRating = this.getOne(queryWrapper);
        
        if (existingRating != null) {
            // 如果已存在，则更新评分
            existingRating.setScore(rating.getScore());
            return this.updateById(existingRating);
        } else {
            // 如果不存在，则插入新评分
            return this.save(rating);
        }
    }
}
